const path = require("node:path");
const fs = require("node:fs");

const express = require("express");
const multer = require("multer");

const port = 3000
const app = express();
app.listen(port, "localhost", () => {
  console.log(`监听 ${port} 端口成功`); //监听成功执行的回调函数
  console.log("\n--------\n"); //监听成功执行的回调函数
});

//实例化multer，传递的参数对象，dest表示上传文件的存储路径
const objMulter = multer({
  dest: "./oss",
  limits: {
    fileSize: 1024 * 1024 * 0.4,
    files: 1,
  },
  fileFilter: function (req, file, cb) {
    console.log("file.mimetype", file.mimetype);
    // 限制文件上传类型，仅可上传png格式图片
    const limits = ["image/png", "image/jpg", "image/jpeg"];
    if (limits.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(null, false);
    }
  },
});

app.use("/public/file_oss", express.static("./oss")); // 将静态资源托管，这样才能在浏览器上直接访问预览图片或则html页面

app.post("/api/upload", objMulter.any(), (req, res) => {
  const file = req.files[0];
  if (file) {
    const oldName = file.path; //获取名字
    const ext = path.parse(file.originalname).ext;
    //给新名字加上原来的后缀
    let newName = oldName + ext;
    //改图片的名字
    fs.renameSync(oldName, newName);
    //该图片的预览路径
    const url = file.filename + ext;
    res.send({
      err: 0,
      message: "上传成功",
      url, //该图片的预览路径
    });
  } else {
    res.send({
      err: 1,
      message: "请选择文件",
    });
  }
});
